<?php
class UserController extends Zend_Controller_Action
{
    public function loginProtectedAction() {
        $username = $this->getRequest()->getParam('username');
        $password = $this->getRequest()->getParam('password');
        if($username=='pearson' && $password=='pearson@123') {
            $pretty_protected = new Zend_Session_Namespace('pretty_protected');
            // expire only this variable
            $pretty_protected->setExpirationSeconds(900, 'accept_answer');
            $pretty_protected->accept_answer = true;
            echo 1;
        }else {
            echo 0;
        }
        exit;
    }
    
    public function login112Action()
    {
        $auth = My\Auth::getInstance();
        $providers = $auth->getIdentity();

        // Here the response of the providers are registered
        if ($this->_hasParam('provider')) {
            $provider = $this->_getParam('provider');

            switch ($provider) {
                case "facebook":
                    if ($this->_hasParam('code')) {
                        $adapter = new My\Auth\Adapter\Facebook(
                                $this->_getParam('code'));
                        $result = $auth->authenticate($adapter);
                    }
                    if($this->_hasParam('error')) {
                        throw new Zend_Controller_Action_Exception('Facebook login failed, response is: ' . 
                            $this->_getParam('error'));
                    }
                    break;
                case "twitter":
if ($this->_hasParam('oauth_token')) {
    require('My/twitteroauth/twitteroauth.php');

    $options = Zend_Registry::get('config');
    $consumerKey = $options['twitter']['consumerKey'];
    $consumerSecret = $options['twitter']['consumerSecret'];
    
    /* If the oauth_token is old redirect to the connect page. */
    if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
      $_SESSION['oauth_status'] = 'oldtoken';
      session_destroy();
      $this->redirect('/index');
    }
    
    /* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
    $connection = new TwitterOAuth($consumerKey, $consumerSecret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
    
    /* Request access tokens from twitter */
    $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
    
    /* Save the access tokens. Normally these would be saved in a database for future use. */
    $_SESSION['access_token'] = $access_token;
    
    /* Remove no longer needed request tokens */
    unset($_SESSION['oauth_token']);
    unset($_SESSION['oauth_token_secret']);
    
    /* If HTTP response is 200 continue otherwise send to connect page to retry */
    if (200 == $connection->http_code) {
      /* The user has been verified and the access tokens can be saved for future use */
      $_SESSION['status'] = 'verified';
      header('Location: ./index.php');
    } else {
      /* Save HTTP status for error dialog on connnect page.*/
      session_destroy();
      $this->redirect('/index');
    }

print_r($content);exit;
}
break;
/*
                    if ($this->_hasParam('oauth_token')) {
                        $adapter = new My\Auth\Adapter\Twitter($_GET);
                        $result = $auth->authenticate($adapter);
                    }
                    break;
*/
                case "google":
                    if ($this->_hasParam('code')) {
                        $adapter = new My\Auth\Adapter\Google(
                                $this->_getParam('code'));
                        $result = $auth->authenticate($adapter);
                    }
                    if($this->_hasParam('error')) {
                        throw new Zend_Controller_Action_Exception('Google login failed, response is: ' . 
                            $this->_getParam('error'));
                    }
                    break;

            }
            // What to do when invalid
            if (isset($result) && !$result->isValid()) {
                $auth->clearIdentity($this->_getParam('provider'));
                throw new Zend_Controller_Action_Exception('Login failed');
            } else {
                $this->_redirect('/user/connect');
            }
        } else { // Normal login page
            $this->view->googleAuthUrl = My\Auth\Adapter\Google::getAuthorizationUrl();
            $this->view->googleAuthUrlOffline = My\Auth\Adapter\Google::getAuthorizationUrl(true);
            $this->view->facebookAuthUrl = My\Auth\Adapter\Facebook::getAuthorizationUrl();

            $this->view->twitterAuthUrl = \My\Auth\Adapter\Twitter::getAuthorizationUrl();
        }
    }

    public function loginTwitterAction()
    {
        $sessionTwitter = new Zend_Session_Namespace('oauth_token_twitter');
        if ($this->_hasParam('oauth_token')) {
            require('My/Twitteroauth/twitteroauth.php');
        
            $options = Zend_Registry::get('config');
            $consumerKey = $options['twitter']['consumerKey'];
            $consumerSecret = $options['twitter']['consumerSecret'];

            /* If the oauth_token is old redirect to the connect page. */
            if (isset($_REQUEST['oauth_token']) && $sessionTwitter->oauth_token !== $_REQUEST['oauth_token']) {
                $_SESSION['oauth_status'] = 'oldtoken';
                session_destroy();
                $this->redirect('/index');
            }
            
            /* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
            $connection = new TwitterOAuth($consumerKey, $consumerSecret, $sessionTwitter->oauth_token, $sessionTwitter->oauth_token_secret);
            
            /* Request access tokens from twitter */
            $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
            
            /* Save the access tokens. Normally these would be saved in a database for future use. */
            $_SESSION['access_token'] = $access_token;
            
            /* Remove no longer needed request tokens */
            //unset($_SESSION['oauth_token']);
            //unset($_SESSION['oauth_token_secret']);
            Zend_Session::namespaceUnset('oauth_token_twitter');
            
            /* If HTTP response is 200 continue otherwise send to connect page to retry */
            if (200 == $connection->http_code) {
                /* The user has been verified and the access tokens can be saved for future use */
                $_SESSION['status'] = 'verified';
                
                /* Get user access tokens out of the session. */
                $access_token = $_SESSION['access_token'];
                
                /* Create a TwitterOauth object with consumer/user tokens. */
                $connection = new TwitterOAuth($consumerKey, $consumerSecret, $access_token['oauth_token'], $access_token['oauth_token_secret']);
                
                /* If method is set change API call made. Test is called by default. */
                $content = $connection->get('account/verify_credentials');
        //print_r($content);exit;
                $providerName = "twitter";
                $providerId = $content->id;
                $profile = array('email' => $content->screen_name);
                
                $this->autoRegister($profile, $providerName, $providerId);
            } else {
                /* Save HTTP status for error dialog on connnect page.*/
                session_destroy();
                $this->redirect('/');
            }
        }


        $this->_redirect('/');
    }
    
    public function connectTwitterAction() 
    {
        require('My/Twitteroauth/twitteroauth.php');
        $options = Zend_Registry::get('config');
        $consumerKey = $options['twitter']['consumerKey'];
        $consumerSecret = $options['twitter']['consumerSecret'];
        $callbackUrl = $options['twitter']['callbackUrl'];
        
        /* Build TwitterOAuth object with client credentials. */
        $connection = new TwitterOAuth($consumerKey, $consumerSecret);
        
        /* Get temporary credentials. */
        $request_token = $connection->getRequestToken($callbackUrl);
        
        $sessionTwitter = new Zend_Session_Namespace('oauth_token_twitter');
        $sessionTwitter->oauth_token = $token = $request_token['oauth_token'];
        $sessionTwitter->oauth_token_secret = $request_token['oauth_token_secret'];
        
        /* If last connection failed don't display authorization link. */
        switch ($connection->http_code) {
          case 200:
            /* Build authorize URL and redirect user to Twitter. */
            $url = $connection->getAuthorizeURL($token);
            header('Location: ' . $url); 
            break;
          default:
            /* Show notification if something went wrong. */
            echo 'Could not connect to Twitter. Refresh the page or try again later.';
        }
        
        //$this->_redirect('/');
        exit;
    }
    
    public function logoutProviderAction()
    {
        \My\Auth::getInstance()->clearIdentity();
        $user = new Application_Model_User();
        print_r($user->getSession());
        Zend_Session::namespaceUnset('zs_User_2pretty');
        session_destroy();
        $this->_redirect('/');
    }

    public function connectAction()
    {
        $auth = My\Auth::getInstance();
        if (!$auth->hasIdentity()) {
            throw new Zend_Controller_Action_Exception('Not logged in!', 404);
        }
        $this->view->providers = $auth->getIdentity();
    }
    
    function loginAction()
    {
        $request = $this->getRequest();
        $email = addslashes($request->getParam('email'));
        $password = $request->getParam('password');
        $user = new Application_Model_User();
        $user->login($email, $password);
        if ($user->isLoggedIn()) {
            $this->_redirect('/');
        } else {
            $this->_redirect('/');
        }
    }

    public function loginFacebookAction()
    {
        $auth = My\Auth::getInstance();
        $providers = $auth->getIdentity();

        if ($this->_hasParam('code')) {
            $adapter = new My\Auth\Adapter\Facebook(
                    $this->_getParam('code'));
            $result = $auth->authenticate($adapter);
        }
        if($this->_hasParam('error')) {
            throw new Zend_Controller_Action_Exception('Facebook login failed, response is: ' . 
                $this->_getParam('error'));
        }

        // What to do when invalid
        if (isset($result) && !$result->isValid()) {
            $auth->clearIdentity($this->_getParam('provider'));
            throw new Zend_Controller_Action_Exception('Login failed');
        } else {
            //$this->_redirect('/user/connect');
            if (!$auth->hasIdentity()) {
                throw new Zend_Controller_Action_Exception('Not logged in!', 404);
            }
            //$this->view->providers = $auth->getIdentity();
            $providers = $auth->getIdentity();
            foreach ($providers as $provider) {
                $profile = $provider->getApi()->getProfile(); 
                $this->autoRegister($profile, $provider->getName(), $provider->getId());
            }
        }
        
        $this->_redirect('/');
    }

    public function loginGoogleAction()
    {
        $auth = My\Auth::getInstance();
        $providers = $auth->getIdentity();
        
        if ($this->_hasParam('code')) {
            $adapter = new My\Auth\Adapter\Google(
                    $this->_getParam('code'));
            $result = $auth->authenticate($adapter);
        }
        if($this->_hasParam('error')) {
            throw new Zend_Controller_Action_Exception('Google login failed, response is: ' . 
                $this->_getParam('error'));
        }
        
        // What to do when invalid
        if (isset($result) && !$result->isValid()) {
            $auth->clearIdentity($this->_getParam('provider'));
            throw new Zend_Controller_Action_Exception('Login failed');
        } else {
            //$this->_redirect('/user/connect');
            if (!$auth->hasIdentity()) {
                throw new Zend_Controller_Action_Exception('Not logged in!', 404);
            }
            //$this->view->providers = $auth->getIdentity();
            $providers = $auth->getIdentity();
            foreach ($providers as $provider) {
                $profile = $provider->getApi()->getProfile(); 
//print_r($profile);exit;
                $this->autoRegister($profile, $provider->getName(), $provider->getId());
            }
        }
        
        $this->_redirect('/');
    }
    
    public function checkLoginAction()
    {
        $request = $this->getRequest();
        $email = addslashes($request->getParam('email'));
        $password = $request->getParam('password');
        $user = new Application_Model_User();
        $user->login($email, $password);
        if ($user->isLoggedIn()) {
            echo 1;
        } else {
            echo 0;
        }
        exit;
    }

    
    public function logoutAction()
    {
        //session_unset();
        $user = new Application_Model_User();
        print_r($user->getSession());
        Zend_Session::namespaceUnset('zs_User_2pretty');
        Zend_Session::namespaceUnset('twitterToken');
        $this->_redirect('/');
    }
    
    public function registerAction()
    {
        $post = $this->getRequest()->getPost();
        $userModel = new Application_Model_User();

        if($post['registration']) {

            $data = array(
                'email'       => $post['email1'],
                'password'    => md5($post['password1']),
                'created_date'=> date('Y-m-d H:i:s')
            );
            
            if($post['user_id']) {
                unset($data['created_date']);
                $userModel->update($data, 'user_id=' . $post['user_id']);
            } else {
                $userDetailModel = new Application_Model_UserDetail();
                $userId = $userModel->insert($data);
                $userModel->update(array('user_code' => $userId + 1000), 'user_id=' . $userId);
                
                $dataDetail = array(
                    'user_id'    => $userId,
                    'address'    => $post['address'],
                    'first_name' => $post['first_name'],
                    'last_name'  => $post['last_name'],
                );
                
                $userDetailModel->insert($dataDetail);
                $this->view->msg = 'You registered successfully. Please to login and update your profile.';
            }
        }
    }
    
    public function forgotPasswordAction()
    {
        if( $this->_request->isPost() ){
            $userModel = new Application_Model_User();
            $email = $this->getRequest()->getParam('email1', '');

            if( !empty($email) ) $row = $userModel->_existsUser($email);
            if( $row['user_id'] ){
                $options = \Zend_Registry::get('config');
                /*
                $data = array(
                    "content"    => "New your password is 123456.",
                    "fromMail"    => $options['mail']['email'],
                    "fromName"    => "Pretty",
                    "toMail"    => $email,
                    "toName"    => 'Member',
                    "subject"    => "Pretty - Forgot password"
                );
                $result = My\Mail::sendMail($data);
                */
                
                $mail = new Zend_Mail();
                $mail->setFrom('no-reply@2pretty.com');
                $mail->setBodyHtml('New your password is 123456.');
                $mail->addTo($email, 'Member');
                $mail->setSubject('2Pretty - Forgot password');
                $result = $mail->send();
                
                if($result) { 
                    $userModel = new Application_Model_User();
                    $userModel->update(array('password' => md5('123456')), 'user_id="'. $row['user_id'] .'"');
                    
                    $this->view->msg = 'We sent a email reset password to you.';
                }
            } else {
                 $this->view->msg = 'Your email is not exists.';
            }
        }
    }
    
    public function autoRegister($data, $providerName, $providerId)
    {
        if(is_object($data)) {
            $data = (array) $data;
        }

        $userModel = new Application_Model_User();
        $row = $userModel->_loadByUserNameProvider($data['name'], $providerName);
        if(!$row['user_id']) {
            $user = array(
                'email'            => $data['name'],
                'provider'         => $providerName,
                'provider_user_id' => $providerId,
                'created_date'     => date('Y-m-d H:i:s')
            );
            
            $userId = $userModel->insert($user);
//echo $userId;exit;
            $userModel->update(array('user_code' => $userId + 1000), 'user_id=' . $userId);
        }
        
        $userModel->loginProvider($data['name'], $providerName);
    }
    
    public function viewProfileAction()
    {
        $userId = $this->getRequest()->getParam('member');
        $userModel = new Application_Model_User();
        $userInfo = $userModel->getDetailUser($userId);
        
        $directory = APPLICATION_PATH . '/../public/images/users/'. $userId;
        //$listImage = $this->getDirectoryList($directory);
        //print_r($listImage);
        //$this->view->listImage = $listImage;
        $this->view->userInfo = $userInfo;
        
        //$this->forward('index', 'profile');
        $this->renderScript('profile/index.phtml');
    }
}
